package TestSparkConversionOperator.KeyValuePairRDD;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.List;

public class SparkSortByKey {
    public static void main(String[] args) {
        /**
         * 根据key对键值对RDD进行排序，返回一个排序好的键值对RDD。
         * 默认是升序，如果传递一个参数false，则是按照降序排序
         */
        SparkConf sparkConf = new SparkConf().setAppName("SparkMapTOPair").setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(sparkConf);
        List<String> data = Arrays.asList("a,47", "b,46","c,48");
        JavaRDD<String> rdd1 = sc.parallelize(data);

        JavaPairRDD<String, String> pairRDD = rdd1.mapToPair(new PairFunction<String, String, String>() {
            @Override
            public Tuple2<String, String> call(String s) throws Exception {

                return new Tuple2<>(s.split(",")[0], s);
            }
        });
        JavaPairRDD<String, String> newRdd = pairRDD.sortByKey(false);
        System.out.println(newRdd.collect());
    }
}
